<template>
  <div class="about">
    <div class="container">
      <div style="margin: 20px 0">
        <el-input placeholder="请输入用户名" v-model="username" style="width: 200px;"></el-input>
        <el-input placeholder="请输入姓名" v-model="name" style="width: 200px; margin: 0 10px"></el-input>
        <el-button type="primary" @click="load(pageNum)">查询</el-button>
        <el-button type="warning" @click="returnInfo">重置</el-button>
      </div>

      <div style="margin: 20px 0">
        <el-button type="primary" @click="FormAddInfoAn" plain>添加数据</el-button>
        <el-button type="danger" @click="deleteBatch">批量删除</el-button>
        <el-button type="success" @click="exportExcel" plain>导出Excel</el-button>
        <el-upload
            style="display: inline-block;
            margin-left: 10px"
            type="info"
              :on-success="handleImport"
            action="http://localhost:9090/user/import"
            :headers="{token: user.token}"
            :show-file-list="false"
        >
          <el-button type="info">导入Excel</el-button>
        </el-upload>
      </div>

      <el-table :data="tableData" @selection-change="handleSelectionChange" style="border-radius: 10px"
                :header-cell-style="{background:'aliceblue',height:'45px', color:'#666'}">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column align="center" prop="username" label="用户名"></el-table-column>
        <el-table-column align="center" prop="name" label="姓名"></el-table-column>
        <el-table-column align="center" prop="phone" label="电话"></el-table-column>
        <el-table-column align="center" prop="email" show-overflow-tooltip label="邮件"></el-table-column>
        <el-table-column align="center" prop="address" show-overflow-tooltip label="地址"></el-table-column>
        <el-table-column align="center" prop="role" label="身份"></el-table-column>
        <el-table-column align="center" prop="avatar" label="头像">
          <template slot-scope="scope">
            <el-image
                style="width: 60px; border-radius: 50%; height: 60px"
                :src="scope.row.avatar"
                :preview-src-list="[scope.row.avatar]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" width="170px" label="操作">
          <template v-slot="scope" style="width: 340px">
            <el-button style="width: 65px; margin-right: 10px" type="success" plain @click="handleEdit(scope.row)">编辑
            </el-button>
            <el-button style="width: 65px;" type="danger" plain @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin: 20px 0">
        <el-pagination
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>

      <el-dialog title="添加用户" :visible.sync="FormAddInfo" width="40%">
        <el-form label-width="80px" style="padding-right: 30px" ref="formRef" :rules="rules" :model="users"
                 class="demo-form-inline">
          <div style="text-align: center">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:9090/file/upload"
                :show-file-list="false"
                :headers="{token: user.token}"
                :on-success="handleAvatarSuccess"
            >
              <img v-if="users.avatar" :src="users.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>

          <el-form-item prop="username" style="margin-top: 30px;" label="用户名">
            <el-input v-model="users.username"></el-input>
          </el-form-item>

          <el-form-item prop="name" style="margin-left: 2px" label="姓名">
            <el-input v-model="users.name"></el-input>
          </el-form-item>

          <el-form-item prop="phone" style=" margin-left: 2px" label="电话">
            <el-input v-model="users.phone"></el-input>
          </el-form-item>

          <el-form-item prop="email" style=" margin-left: 2px" label="邮箱">
            <el-input v-model="users.email"></el-input>
          </el-form-item>

          <el-form-item prop="address" style=" margin-left: 2px" label="地址">
            <el-input type="textarea" v-model="users.address"></el-input>
          </el-form-item>

          <el-form-item prop="role" style="align-items: center">
            <el-radio-group v-model="users.role">
              <el-radio label="用户"></el-radio>
              <el-radio label="商家"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>

        <div slot="footer" style="text-align: center; margin-top: -10px">
          <el-button @click="FormAddInfo = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </div>

      </el-dialog>

      <el-dialog title="修改用户" :visible.sync="FormUpdateInfo" width="40%">
        <el-form label-width="80px" style="padding-right: 30px" ref="formRef" :rules="rules" :model="forms"
                 class="demo-form-inline">
          <div style="text-align: center">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:9090/file/upload"
                :show-file-list="false"
                :headers="{token: user.token}"
                :on-success="handleAvatarSuccessFrom"
            >
              <img v-if="forms.avatar" :src="forms.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>

          <el-form-item prop="username" style="margin-top: 30px;" label="用户名">
            <el-input v-model="forms.username" disabled></el-input>
          </el-form-item>

          <el-form-item prop="name" style="margin-left: 2px" label="姓名">
            <el-input v-model="forms.name"></el-input>
          </el-form-item>

          <el-form-item prop="phone" style=" margin-left: 2px" label="电话">
            <el-input v-model="forms.phone"></el-input>
          </el-form-item>

          <el-form-item prop="email" style=" margin-left: 2px" label="邮箱">
            <el-input v-model="forms.email"></el-input>
          </el-form-item>

          <el-form-item prop="address" style=" margin-left: 2px" label="地址">
            <el-input type="textarea" v-model="forms.address"></el-input>
          </el-form-item>

          <el-form-item prop="role" style="align-items: center">
            <el-radio-group v-model="forms.role" disabled>
              <el-radio label="用户"></el-radio>
              <el-radio label="商家"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>

        <div slot="footer" style="text-align: center; margin-top: -10px">
          <el-button @click="FormUpdateInfo = false">取 消</el-button>
          <el-button type="primary" @click="onUpdate">确 定</el-button>
        </div>

      </el-dialog>

    </div>
  </div>
</template>

<script>
import request from "@/utils/request"

export default {
  data() {
    return {
      Info: JSON.parse(localStorage.getItem('user11') || '{}'),
      pageSize: 5,
      pageNum: 1,
      tableData: [],
      username: '',
      name: '',
      total: 0,
      FormAddInfo: false,
      user: JSON.parse(localStorage.getItem('user11') || '{}'),
      users: {
        avatar: '',
        username: '',
        phone: '',
        email: '',
        address: '',
        name: '',
        role: '',
      },
      ids: [],
      forms: {
        avatar: '',
        username: '',
        phone: '',
        email: '',
        address: '',
        name: '',
        role: '',
      },
      FormUpdateInfo: false,

      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 4 个字符', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.load()
  },
  methods: {

    //批量导出
    handleImport(res,file,fileList) {

      if (res.code === 200) {
        this.$message({type: 'success', message: '导入成功'});
        this.load(1)
      } else {
        this.$message.error(res.message)
      }
    },

    //批量导出
    exportExcel() {
      //导出全部数据
      if (this.ids.length === 0) {
        this.$confirm('确定全部导出吗？', '提示', {type: 'warning'}).then(() => {
          window.open('http://localhost:9090/user/export?token=' + this.user.token + '&username=' + this.username + '&name=' + this.name)
        }).catch(() => {
          this.$message({type: 'info', message: '已取消导出'});
        })
      } else {
        this.$confirm('确定导出选择的数据吗？', '提示', {type: 'warning'}).then(() => {
          let idStr = this.ids.join(',')
          window.open('http://localhost:9090/user/export?token=' + this.user.token + '&ids=' + idStr)
        }).catch(() => {
          this.$message({type: 'info', message: '已取消导出'});
        })
      }
    },

    //批量删除
    deleteBatch() {
      if(this.ids.length === 0) {
        this.$message.warning('请选择要批量删除的数据')
        return
      }
      // 遍历this.ids与this.Info.id进行对比，如果有重复的请停止下面操作给出提示并返回
      for (let i = 0; i < this.ids.length; i++) {
        if (this.Info.id === this.ids[i]) {
          this.$message.error('批量删除包含当前登录的用户,请重新选择')
          return
        }
      }
      this.$confirm('确定批量删除吗？', '提示', {type: 'warning'}).then(() => {
        request.delete('/user/deleteBatch', {
          data:this.ids
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('批量删除成功')
            this.load(1)
          } else {
            // 登录失败
            this.$message.error(res.message)
          }
        })
      }).catch(() => {
        this.$message({type: 'info', message: '已取消批量删除'});
      })
    },

    //批量删除获取数据
    handleSelectionChange(rows) {
        // 提取所有选中的 id 并拼接成字符串
        this.ids = rows.map(v => v.id);
    },

    FormAddInfoAn() {
      this.FormAddInfo = true,
          this.users = {}
    },

    //删除单条数据
    handleDelete(id) {
      if (this.Info.id == id) {
        this.$message.error('不能删除当前登录的用户')
        return
      }
      this.$confirm('确定删除吗？', '提示', {type: 'warning'}).then(() => {
        request.delete('/user/delete/' + id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.load(1)
          } else {
            // 登录失败
            this.$message.error(res.message)
          }
        })
      }).catch(() => {
        this.$message({type: 'info', message: '已取消删除'});
      })
    },

    //编辑数据
    handleEdit(row) {
      this.FormUpdateInfo = true,
          this.forms = JSON.parse(JSON.stringify(row))
    },
    //确认是否确认提交修改
    onUpdate() {
      this.$confirm('确定用户信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //触发更新
        request.post('/user/update', this.forms).then(res => {
          if (res.code === 200) {
            this.$message.success('修改成功')
            //  浏览器页面自动更新
            this.FormUpdateInfo = false
            this.load()
          } else {
            // 登录失败
            this.$message.error(res.message)
          }
        })
      }).catch(() => {
        this.$message({type: 'info', message: '已取消修改'});
      })
    },

    returnInfo() {
      this.username = '',
          this.name = '',
          this.load()
    },
    load(pageNum) {
      this.pageNum = pageNum || 1
      request.get('/user/selectByPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          username: this.username,
          name: this.name,
        }
      }).then(res => {
        this.tableData = res.data.list
        this.total = res.data.total
      })
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },

    //  添加表单
    onSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.$confirm('再次确定添加用户信息？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            //触发更新
            reuqest.post('/user/add', this.users).then(res => {
              if (res.code === 200) {
                this.$message.success('添加成功')
                //  浏览器页面自动更新
                this.FormAddInfo = false
                this.load()
              } else {
                // 登录失败
                this.$message.error(res.message)
              }
            })
          }).catch(() => {
            this.$message({type: 'info', message: '已取消修改'});
          })
        }
      })
    },
    handleAvatarSuccess(res, file, fileList) {
      this.users.avatar = res.data
    },
    handleAvatarSuccessFrom(res, file, fileList) {
      this.forms.avatar = res.data
    }
  }
}
;
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 140px;
  height: 140px;
  line-height: 140px;
  text-align: center;
  border-radius: 50%;
  margin-top: -10px;
  margin-bottom: 10px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
